package cn.easy.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author 张澎_9970
 * @date 2021.12.15 下午 11:30 星期三
 * @desc:
 */
@Component
@RabbitListener(queues = "Qu_01")
public class AckListener {

    /**
     * @param message
     * @param channel
     * @param msg
     */
    @RabbitHandler
    public void msg(Message message, Channel channel, String msg) {
        System.out.println("接收到的消息: " + message);
        // 模拟处理业务
        try {
            System.out.println("业务开始>>>>");
            Thread.sleep(1000);
            int i = 1 / 0;
            System.out.println("业务结束||||");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                // channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
                // channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException ex) {
                ex.printStackTrace();
                if (message.getMessageProperties().getRedelivered()){
                    System.out.println("已经投递一次了");
                } else {
                    try {
                        channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                    } catch (IOException exc) {
                        exc.printStackTrace();
                    }
                }
            }
        }
    }

    @RabbitHandler
    public void msg(Map mapMsg) {
        System.out.println("接收到的消息: " + mapMsg);
    }
}
